<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\DrainageLink\Listener;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use MoChat\App\Corp\Logic\AppTrait;
use MoChat\App\WorkContact\Event\AddContactEvent;
use MoChat\Plugin\DrainageLink\Contract\DrainageLinkContactContract;
use MoChat\Plugin\DrainageLink\Contract\DrainageLinkContract;

/**
 * 添加企业客户事件.
 *
 * @Listener
 */
class AddContactListener implements ListenerInterface
{
    use AppTrait;

    /**
     * @Inject
     * @var DrainageLinkContract
     */
    protected $drainageLinkService;

    /**
     * @Inject
     * @var DrainageLinkContactContract
     */
    protected $drainageLinkContactService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    public function listen(): array
    {
        return [
            AddContactEvent::class,
        ];
    }

    public function process(object $event)
    {
        try {
            $contact = $event->message;
            $this->handleDrainageLink($contact);
        } catch (\Exception $e) {
            $this->logger->error(sprintf('[引流链接]失败，错误信息: %s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }

    /**
     * 引流链接-用户数据处理.
     * @param mixed $contact
     */
    private function handleDrainageLink($contact): void
    {
        $this->logger->info('引流链接-开始');
        if (! isset($contact['state']) || empty($contact['state']) || ! str_contains($contact['state'], 'channelCode')) {
            return;
        }
        // 渠道id
        $stateArr = explode('-', $contact['state']);
        if (empty($stateArr[1])) {
            return;
        }
        // 渠道活码是否使用在引流链接中
        $drainageLink = $this->drainageLinkService->getDrainageLinkByTypeQrcodeId(1, (int) $stateArr[1], ['id', 'corp_id']);
        if (empty($drainageLink)) {
            return;
        }

        // 开启事物
        Db::beginTransaction();
        try {
            $data = [
                'link_id' => $drainageLink['id'],
                'contact_id' => $contact['id'] ?? 0,
                'created_at' => date('Y-m-d H:i:s'),
            ];
            $this->drainageLinkContactService->createDrainageLinkContact($data);

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            // 记录错误日志
            $this->logger->error(sprintf('%s [%s] %s', '引流链接-数据处理失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }
}
